package com.alogic.validator.impl;

import com.alogic.validator.Validator;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;

/**
 * 长度限制验证器
 * @author yyduan
 * @since 1.6.12.12 [20181207 duanyy] <br>
 *
 * @version 1.6.13.17 [20200923 duanyy] <br>
 * - 优化validator接口
 * @version 1.6.13.25 [20201110 duanyy] <br>
 * - 修复validator的问题
 */
public class LengthLimit extends Validator.Abstract{
	protected int from = 1;
	protected int to = Integer.MAX_VALUE;
	@Override
	public void configure(Properties p) {
		super.configure(p);
		from = PropertiesConstants.getInt(p,"from",from,true);
		to = PropertiesConstants.getInt(p,"to",to,true);		
	}	
	
	@Override
	public boolean check(String value, Properties ctx,boolean throwException) {
		int length = value.length();
		boolean result =  length >= from && length <= to;
		if (!result && throwException){
			throw new BaseException(getCode(ctx),getMessage(ctx));
		}
		return result;
	}

	@Override
	public boolean check(String value, Properties ctx, Listener listener) {
		int length = value.length();
		boolean result = length >= from && length <= to;
		if (listener != null){
			listener.result(result,value,this,ctx);
		}
		return result;
	}
}

